package com.staginfo.segs.function.registerOrLogin.login.view;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.staginfo.segs.MainActivity;
import com.staginfo.segs.R;
import com.staginfo.segs.base.BaseActivity;
import com.staginfo.segs.common.Config;
import com.staginfo.segs.common.Constants;
import com.staginfo.segs.function.registerOrLogin.login.LoginConstruct.LoginConstruct;
import com.staginfo.segs.function.registerOrLogin.login.bean.AuthenticateStatus;
import com.staginfo.segs.function.registerOrLogin.login.presenter.UserLoginPresenter;
import com.staginfo.segs.util.IPCheckUtil;
import com.staginfo.segs.util.ToastUtil;


import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by robert.luozizhao on 2017/9/5 0005.
 */
//Tony

public class UserLoginActivity extends BaseActivity implements LoginConstruct.LoginView<AuthenticateStatus> {

//代码编写完成
    @Bind(R.id.et_username)
    EditText etUsername;
    @Bind(R.id.et_password)
    EditText etPassword;
    @Bind(R.id.btnLogin)
    Button btnLogin;
    @Bind(R.id.showText)
    TextView showText;
    @Bind(R.id.forgetPassword)
    TextView forgetPassword;
    @Bind(R.id.register)
    TextView register;
    @Bind(R.id.tv_serverSetting)
    TextView tvServerSetting;
    @Bind(R.id.et_settingSerUrl)
    EditText etSettingSerUrl;
    @Bind(R.id.setting_url)
    Button settingUrl;

    private UserLoginPresenter mUserLoginPresenter;
    private ProgressDialog mProgressDialog;
    private String mTrim;  // 输入的ip地址

    @Override
    public int getLayout() {
        return R.layout.activity_login;
    }

    @Override
    public void initView() {
        super.initView();
        mProgressDialog = new ProgressDialog(this);
        IPCheckUtil.setEditTextInhibitInputSpace(etSettingSerUrl);
        IPCheckUtil.setEditTextInhibitInputSpeChat(etSettingSerUrl);
        etSettingSerUrl.setHint(Config.getConfiguredServer(this));
    }


    @Override
    public void initData() {
        super.initData();

        if (Build.VERSION.SDK_INT > 22) {
            getReadWritePermission();
        }

    }



    @OnClick({R.id.forgetPassword, R.id.register, R.id.btnLogin, R.id.tv_serverSetting, R.id.et_settingSerUrl,R.id.setting_url})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.forgetPassword:

                break;
            case R.id.register:

                break;
            case R.id.btnLogin:
                mUserLoginPresenter = new UserLoginPresenter(this);
                mUserLoginPresenter.login();
                mProgressDialog.show();
                break;

            case R.id.tv_serverSetting:

                break;

            case R.id.et_settingSerUrl:

                break;

            case R.id.setting_url:
                if (CheckIPAddress()) {
                    Config.setDefaultServer(this,mTrim);
                }
                break;
        }
    }

    private boolean CheckIPAddress() {
        mTrim = etSettingSerUrl.getText().toString().trim();
        if (TextUtils.isEmpty(mTrim)) {
            ToastUtil.getInstance(this).shortToast("ip地址不能为空！");
            return false;
        }else if(!IPCheckUtil.isIPAddress(mTrim)){
            ToastUtil.getInstance(this).shortToast("你输入的ip地址不正确！");
            return false;
        }
        return true;
    }





    @Override
    public void loginSuccess(AuthenticateStatus data) {
        //1 停止进度条  2 成功展示
        mProgressDialog.dismiss();
//        showText.setText(data.toString());

        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();

    }

    @Override
    public void loginFailed(int method, int statusCode) {
        //1 停止进度条  2 失败展示
        mProgressDialog.dismiss();
        showText.setText("loginFailed statusCode = " + statusCode + ", method = " + method);
    }


    @Override
    public String getUsername() {
        return etUsername.getText().toString().trim();
    }

    @Override
    public String getPassword() {
        return etPassword.getText().toString().trim();
    }


    @Override
    public void refreshData(AuthenticateStatus data) {

    }


    private void getReadWritePermission() {
        if (
                ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                        || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            btnLogin.setEnabled(false);
//            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
//                    Manifest.permission.READ_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(this,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
//
//            } else {
//                Toast.makeText(this, "请授予存储权限，否则可能导致异常", Toast.LENGTH_SHORT).show();
//            }
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                    Constants.REQUEST_PERMISSION_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Constants.REQUEST_PERMISSION_EXTERNAL_STORAGE) {
            if (grantResults.length < 2)
                return;
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED
                    && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
                btnLogin.setEnabled(true);
            } else {
                Toast.makeText(this, R.string.toast_grant_permission, Toast.LENGTH_SHORT).show();
            }
        }
    }



}
